<template>
  <div class="table-box">
    <ProTable
      ref="proTableRef"
      title="员工用户表"
      :indent="20"
      :columns="columns"
      :search-columns="searchColumns"
      :request-api="getTableList"
      row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="'sys.user.employee.create'" :icon="CirclePlus" @click="openAddEdit('新增员工用户表')">
          新增
        </el-button>
        <el-button
          v-auth="'sys.user.employee.remove'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
        <el-button v-auth="'sys.user.employee.import'" type="primary" :icon="Upload" plain @click="importData"> 导入 </el-button>
        <el-button v-auth="'sys.user.employee.export'" type="primary" :icon="Download" plain @click="downloadFile">
          导出
        </el-button>
      </template>
      <template #operation="{ row }">
        <el-button
          v-auth="'sys.user.employee.update'"
          type="primary"
          link
          :icon="EditPen"
          @click="openAddEdit('编辑员工用户表', row, false)"
        >
          编辑
        </el-button>
        <el-button v-auth="'sys.user.employee.remove'" type="primary" link :icon="Delete" @click="deleteInfo(row)">
          删除
        </el-button>
      </template>
    </ProTable>
    <SysUserEmployeeForm ref="sysUserEmployeeRef" />
    <ImportExcel ref="ImportExcelRef" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { CirclePlus, Delete, EditPen, Upload, Download } from '@element-plus/icons-vue';
import ProTable from '@/components/ProTable/index.vue';
import {
  createSysUserEmployeeApi,
  removeSysUserEmployeeApi,
  updateSysUserEmployeeApi,
  getSysUserEmployeeListApi,
  getSysUserEmployeeDetailApi,
  importSysUserEmployeeExcelApi,
  exportSysUserEmployeeExcelApi
} from '@/api/modules/sysuseremployee/sysUserEmployee';
import { useHandleData } from '@/hooks/useHandleData';
import SysUserEmployeeForm from '@/views/sysuseremployee/sysUserEmployee/components/SysUserEmployeeForm.vue';
import { useDictOptions } from '@/hooks/useDictOptions';
import type { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface';
import type { SysUserEmployeeQuery, SysUserEmployeeRow } from '@/api/types/sysuseremployee/sysUserEmployee';
import ImportExcel from '@/components/ImportExcel/index.vue';
import { downloadTemplate } from '@/api/modules/system/common';
import { useDownload } from '@/hooks/useDownload';
import { useDict } from '@/hooks/useDict';
defineOptions({
  name: 'SysUserEmployeeView'
});
// 使用useDict Hook 主动加载字典
useDict(['user_tag', 'dynamic_user_options', 'account_status']);
const proTableRef = ref<ProTableInstance>();
// 表格配置项
const columns: ColumnProps<SysUserEmployeeRow>[] = [
  { type: 'selection', width: 80 },
  { prop: 'username', label: '用户名' },
  { prop: 'pwd', label: '密码' },
  { prop: 'phone', label: '手机号' },
  { prop: 'nickname', label: '昵称' },
  { prop: 'sex', label: '性别(0 未知 1 男 2 女)' },
  { prop: 'birthday', label: '生日' },
  { prop: 'logo', label: '头像地址' },
  { prop: 'age', label: '年龄，--废弃，以生日为主' },
  { prop: 'idCard', label: '身份证' },
  { prop: 'email', label: '邮箱地址' },
  {
    prop: 'accountStatusCd',
    label: '账户状态 (如 冻结；禁言；正常。 关联字典表account_status)',
    tag: true,
    enum: useDictOptions('account_status'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  },
  {
    prop: 'userTagCd',
    label: '标签（自定义关联到字典表）',
    tag: true,
    enum: useDictOptions('user_tag'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  },
  { prop: 'lastLoginTime', label: '最近一次登录时间' },
  { prop: 'createTime', label: '创建时间' },
  { prop: 'updateTime', label: '更新时间' },
  {
    prop: 'createId',
    label: '创建人ID',
    tag: true,
    enum: useDictOptions('dynamic_user_options'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  },
  {
    prop: 'updateId',
    label: '更新人ID',
    tag: true,
    enum: useDictOptions('dynamic_user_options'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  },
  { prop: 'operation', label: '操作', width: 250, fixed: 'right' }
];
// 搜索条件项
const searchColumns: SearchProps[] = [
  { prop: 'username', label: '用户名', el: 'input' },
  { prop: 'pwd', label: '密码', el: 'input' },
  { prop: 'phone', label: '手机号', el: 'input' },
  { prop: 'nickname', label: '昵称', el: 'input' },
  { prop: 'sex', label: '性别(0 未知 1 男 2 女)', el: 'select' },
  { prop: 'birthday', label: '生日', el: 'input' },
  { prop: 'logo', label: '头像地址', el: 'input' },
  { prop: 'age', label: '年龄，--废弃，以生日为主', el: 'input' },
  { prop: 'idCard', label: '身份证', el: 'input' },
  { prop: 'email', label: '邮箱地址', el: 'input' },
  {
    prop: 'accountStatusCd',
    label: '账户状态 (如 冻结；禁言；正常。 关联字典表account_status)',
    el: 'select',
    enum: useDictOptions('account_status'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  },
  {
    prop: 'userTagCd',
    label: '标签（自定义关联到字典表）',
    el: 'select',
    enum: useDictOptions('user_tag'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  },
  {
    prop: 'lastLoginTime',
    label: '最近一次登录时间',
    el: 'date-picker',
    span: 2,
    props: {
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss'
    }
  }
];
// 获取table列表
const getTableList = (params: SysUserEmployeeQuery) => {
  let newParams = formatParams(params);
  return getSysUserEmployeeListApi(newParams);
};
const formatParams = (params: SysUserEmployeeQuery) => {
  let newParams = JSON.parse(JSON.stringify(params));
  if (newParams.lastLoginTime) {
    newParams.lastLoginTimeStart = newParams.lastLoginTime[0];
    newParams.lastLoginTimeEnd = newParams.lastLoginTime[1];
    delete newParams.lastLoginTime;
  }

  if (newParams.createTime) {
    newParams.createTimeStart = newParams.createTime[0];
    newParams.createTimeEnd = newParams.createTime[1];
    delete newParams.createTime;
  }

  if (newParams.updateTime) {
    newParams.updateTimeStart = newParams.updateTime[0];
    newParams.updateTimeEnd = newParams.updateTime[1];
    delete newParams.updateTime;
  }

  return newParams;
};
// 打开 drawer(新增、查看、编辑)
const sysUserEmployeeRef = ref<InstanceType<typeof SysUserEmployeeForm>>();
const openAddEdit = async (title: string, row: any = {}, isAdd = true) => {
  if (!isAdd) {
    const record = await getSysUserEmployeeDetailApi({ id: row?.id });
    row = record?.data;
  }
  const params = {
    title,
    row: { ...row },
    api: isAdd ? createSysUserEmployeeApi : updateSysUserEmployeeApi,
    getTableList: proTableRef.value?.getTableList
  };
  sysUserEmployeeRef.value?.acceptParams(params);
};
// 删除信息
const deleteInfo = async (params: SysUserEmployeeRow) => {
  await useHandleData(removeSysUserEmployeeApi, { ids: [params.id] }, `删除【${params.id}】员工用户表`);
  proTableRef.value?.getTableList();
};
// 批量删除信息
const batchDelete = async (ids: (string | number)[]) => {
  await useHandleData(removeSysUserEmployeeApi, { ids }, '删除所选员工用户表');
  proTableRef.value?.clearSelection();
  proTableRef.value?.getTableList();
};
// 导入
const ImportExcelRef = ref<InstanceType<typeof ImportExcel>>();
const importData = () => {
  const params = {
    title: '员工用户表',
    templateName: '员工用户表',
    tempApi: downloadTemplate,
    importApi: importSysUserEmployeeExcelApi,
    getTableList: proTableRef.value?.getTableList
  };
  ImportExcelRef.value?.acceptParams(params);
};
// 导出
const downloadFile = async () => {
  let newParams = formatParams(proTableRef.value?.searchParam as SysUserEmployeeQuery);
  useDownload(exportSysUserEmployeeExcelApi, '员工用户表', newParams);
};
</script>
